package com.bainuo.doctor.common.image_support.imghandle;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.util.Size;

import com.bainuo.doctor.common.image_support.imghandle.crop.ImageCrop;
import com.bainuo.doctor.common.image_support.imghandle.picker.IImagePicker;
import com.bainuo.doctor.common.image_support.imghandle.picker.MulImagePicker;
import com.bainuo.doctor.common.image_support.imghandle.uploader.FileUploader;
import com.bainuo.doctor.common.image_support.imghandle.uploader.IFileUpload;
import com.bainuo.doctor.common.image_support.imghandle.uploader.UploadTask;
import com.bainuo.doctor.common.image_support.imghandle.Bean.ImageUploadInfo;
import com.bainuo.doctor.common.image_support.imghandle.crop.IImageCrop;
import com.bainuo.doctor.common.network_engine.CallBack;
import com.bainuo.doctor.common.network_engine.UpFileServerApi;
import com.bainuo.doctor.common.network_engine.UpLoadFileCallBack;
import com.bainuo.doctor.common.network_engine.UpLoadFileResponse;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by bainuo on 2017/2/10.
 */

public class ImageHandler implements IImagePicker.Listener, IImageCrop.Listener, IFileUpload.Listener {


    /**
     * 相册跳转code
     */
    private int imageRequestCode = 5000;

    /**
     * 系统图片裁剪器跳转code
     */
    public int cropRequestCode = 5001;

    /**
     * 选完图片是否自动上传
     */
    public boolean autoUpload = true;

    public String uploadType;


    public void setImageRequestCode(int imageRequestCode) {
        this.imageRequestCode = imageRequestCode;
        imagePicker.setCode(mActivity, imageRequestCode);
    }

    /**
     * 图片信息map
     */
    Map<String, ImageUploadInfo> infoMap = new HashMap<>();

    private Activity mActivity;

    /**
     * 构造方法 设置requestCode
     */
    public ImageHandler(Activity activity,UpFileServerApi api) {
        initDefaultHandler(activity,api);
    }


    public ImageHandler(Activity activity,int imgCode, int cropCode,UpFileServerApi api) {
        cropRequestCode = imgCode;
        imageRequestCode = cropCode;

        initDefaultHandler(activity,api);

    }

    /**
     * 缺省参数设置
     */
    private void initDefaultHandler(Activity activity,UpFileServerApi api) {
        mActivity = activity;
//        setImagePicker(new SingleImagePicker());
        //设置默认图片选择器
        setImagePicker(new MulImagePicker());
        setImageCrop(new ImageCrop());
        //设置默认图片裁剪器
//        setImageCrop(new ImageAvatarCrop());
        //设置默认图片上传器


        setImageUpload(new FileUploader(api));

        //设置activity 与 code


    }

    public void setUploadFileApi(UpFileServerApi api){
        if (imageUpload != null)
            imageUpload.setUploadApi(api);
    }


    /**
     * 图片选择器接口
     */
    public IImagePicker imagePicker;

    public void setImagePicker(IImagePicker imagePicker) {
        this.imagePicker = imagePicker;
        imagePicker.setPickerCompleteListener(this);
        imagePicker.setCode(mActivity, imageRequestCode);
    }


     private Rect decodeThumbBitmapForFile(String path){

         BitmapFactory.Options options = new BitmapFactory.Options();
         //设置为true,表示解析Bitmap对象，该对象不占内存
         options.inJustDecodeBounds = true;
         BitmapFactory.decodeFile(path,options);
         Rect rect = new Rect(0,0,options.outWidth,options.outHeight);
         return rect;
    }

    /**
     * 图片选择器　回调
     *
     * @param uris
     */
    @Override
    public void onPictureSelected(List<Uri> uris, List<String> paths) {

        //判断 回调是uri 还是path
        List<ImageUploadInfo> list = new ArrayList<>();
        if (uris != null) {
            for (Uri uri : uris) {
                //添加uri
                ImageUploadInfo info = new ImageUploadInfo();
                info.setSrcUri(uri);
                infoMap.put(info.getId(), info);
//                Size size = decodeThumbBitmapForFile(uri);
//                info.setWidth(size.getWidth());
//                info.setHeight(size.getHeight());
                list.add(info);
            }
        } else {
            for (String path : paths) {
                //添加path
                ImageUploadInfo info = new ImageUploadInfo();
                info.setSrcPath(path);
                infoMap.put(info.getId(), info);
                Rect rect = decodeThumbBitmapForFile(path);
                info.setWidth(rect.width());
                info.setHeight(rect.height());
                list.add(info);
            }
        }



        //调用图片选择监听
        if (imagHandlerListener != null)
            imagHandlerListener.onPickerReult(true, list);

        //进行下一步裁剪操作
        for (ImageUploadInfo info : list) {

            //如果有图片裁剪器 则调用裁剪
            if (imageCrop != null)
                imageCrop.cropImage(info);
            else {
                //没有则直接调用裁剪完成
                onCropend(info);
            }
        }
    }


    /**
     * 图片裁剪接口
     */
    public IImageCrop imageCrop;

    public void setImageCrop(IImageCrop imageCrop) {

        this.imageCrop = imageCrop;
        imageCrop.setCropListener(this);
        imageCrop.setCode(mActivity, cropRequestCode);
    }

    @Override
    public void onCropend(ImageUploadInfo info) {

        if (imagHandlerListener != null)
            imagHandlerListener.onImageCropReult(true, info);

        //图片裁剪结束 后 根据 autoUpload 判断是否进行上传
        if (autoUpload && imageUpload != null && info != null) {
            imageUpload.uploadFile(info);
        }
    }


    /**
     * 图片上传器接口
     */
    public IFileUpload imageUpload;

    public void setImageUpload(IFileUpload imageUpload) {
        this.imageUpload = imageUpload;
        imageUpload.setUploadListener(this);
    }

    /**
     * 图片文件上传完成
     */
    @Override
    public void onUploadFinish(UploadTask task) {
        task.setProgress(100);
        onUploadProgress(task);
    }

    /**
     * 服务器返回url
     */
    @Override
    public void onUploadSuccess(UploadTask task) {
        if (imagHandlerListener != null) {

            ImageUploadInfo info = infoMap.get(task.id);

            //调用上传成功结果
            if (info != null)
                imagHandlerListener.onUploadResult(true, info);
        }
    }

    /**
     * 文件上传失败
     */
    @Override
    public void onUploadFailed(UploadTask task) {
        if (imagHandlerListener != null) {
            ImageUploadInfo info = infoMap.get(task.id);
            if (info != null)
                imagHandlerListener.onUploadResult(false, info);
        }
    }

    /**
     * 上传进度
     */
    @Override
    public void onUploadProgress(UploadTask task) {
        if (imagHandlerListener != null) {
            imagHandlerListener.onUploadProgress(task.id, task.getProgress());
        }
    }

    /**
     * 图片处理器回调
     */
    public interface IImagHandlerListener {
        /**
         * 图片选择完成回调
         *
         * @param success
         * @param info
         */
        void onPickerReult(boolean success, List<ImageUploadInfo> info);

        /**
         * 图片裁剪完成回调
         *
         * @param success
         */
        void onImageCropReult(boolean success, ImageUploadInfo info);

        /**
         * 图片上传结果回调
         *
         * @param info
         */
        void onUploadResult(boolean success, ImageUploadInfo info);

        /**
         * 上传进度回调
         */
        void onUploadProgress(String id, int progress);
    }

    /**
     * 文件处理器监听
     */
    private IImagHandlerListener imagHandlerListener;

    public void setImagHandlerListener(IImagHandlerListener imagHandlerListener) {
        this.imagHandlerListener = imagHandlerListener;
    }


    /**
     * 请求重试
     *
     * @param id
     */
//    public void retry(String id) {
//
//        ImageUploadInfo info = infoMap.get(id);
//        if (info != null)
//            imageUpload.uploadFile(info);
//
////        for (ImageUploadInfo info : infoMap.values()){
////            if (info.getId().equals(libPath)){
////
////                break;
////            }
////        }
//
//    }

    /**
     * avtivity 数据回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (imagePicker != null)
            imagePicker.onActivityResult(requestCode, resultCode, data);

        if (imageCrop != null)
            imageCrop.onActivityResult(requestCode, resultCode, data);
    }
}
